package com.lyon.demo.netty.core;

import com.lyon.demo.rpc.api.core.Command;
import com.lyon.demo.rpc.api.core.RespondFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author Lyon
 */
@ChannelHandler.Sharable
@AllArgsConstructor
@Slf4j
public class ResponseInvocation extends ChannelHandlerAdapter {

    private final InFlightRequests inFlightRequests;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Command command = (Command) msg;
        final long requestId = command.getHeader().getRequestId();
        final RespondFuture respondFuture = inFlightRequests.get(requestId);
        if (Objects.nonNull(respondFuture)) {
            respondFuture.getFuture().complete(command);
        } else {
            log.info("messageReceived:failure {}" , requestId);
        }
    }

//    @Override
//    protected void messageReceived(ChannelHandlerContext channelHandlerContext, Command command) throws Exception {
//        //// TODO: 2022/4/15
//
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("ERROR：client-messageReceived", cause);
        super.exceptionCaught(ctx, cause);
        // TODO: 2022/4/15 why ?? 
        if (ctx.channel().isActive()) ctx.close();
    }
}
